package com.dd.cloud.gateway.exception;


import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.vo.ExceptionResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: 异常返回处理
 * @Author: czg
 * @Date: 2023/12/13 10:49
 * @Version: 1.0.0
 */
@Slf4j
public class WebFrameworkUtils {

    private WebFrameworkUtils() {}


    /**
     * @description 网关自定义返回给页面信息 返回json数据
     * @param exchange:
         * @param exceptionResult:
     * @return Mono<Void>
     * @author czg
     * @date 2023/12/13 14:39
    */
    @SuppressWarnings("deprecation")
    public static Mono<Void> writeJSON(ServerWebExchange exchange, ExceptionResult exceptionResult) {
//        // 设置 header
//        ServerHttpResponse response = exchange.getResponse();
//        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
//        ObjectMapper objectMapper = new ObjectMapper();
//        // 设置 body
//        return response.writeWith(Mono.fromSupplier(() -> {
//            DataBufferFactory bufferFactory = response.bufferFactory();
//            try {
//
//                return bufferFactory.wrap(objectMapper.writeValueAsBytes(exceptionResult));
//            } catch (Exception ex) {
//                ServerHttpRequest request = exchange.getRequest();
//                log.error("[writeJSON][uri({}/{}) 发生异常]", request.getURI(), request.getMethod(), ex);
//                return bufferFactory.wrap(new byte[0]);
//            }
//        }));
        ServerHttpResponse response = exchange.getResponse();
//        ExceptionResult exceptionResult = new ExceptionResult(zkEnum);
//        if (!StringUtils.isBlank(message)) {
//            exceptionResult.setMessage(message);
//        }
        response.setStatusCode(HttpStatus.valueOf(exceptionResult.getStatus()));
        DataBufferFactory bufferFactory = response.bufferFactory();
        response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        ObjectMapper objectMapper = new ObjectMapper();
        // 要写入的数据对象，会自动转为json格式
        DataBuffer wrap = null;
        try {
            wrap = bufferFactory.wrap(objectMapper.writeValueAsBytes(exceptionResult));
            DataBuffer finalWrap = wrap;
            return response.writeWith(Mono.fromSupplier(() -> finalWrap));
        } catch (Exception e) {
            DataBuffer finalWrap1 = wrap;
            return response.writeWith(Mono.fromSupplier(() -> finalWrap1));
        }
    }

    /**
     * @param response: 异常response
     * @param zkEnum:   异常枚举
     * @param message:  自定义异常信息,如果为空,则用异常枚举的信息
     * @return Mono<Void> 返回json
     * @description 登录异常返回异常信息 不用这个了
     * @author czg
     * @date 2023/5/16 9:50
     */
    public Mono<Void> resExp(ServerHttpResponse response, ZkExceptionEnum zkEnum, String message) {

        ExceptionResult exceptionResult = new ExceptionResult(zkEnum);
        if (!StringUtils.isBlank(message)) {
            exceptionResult.setMessage(message);
        }
        response.setStatusCode(HttpStatus.valueOf(zkEnum.getCode()));
        DataBufferFactory bufferFactory = response.bufferFactory();
        response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        ObjectMapper objectMapper = new ObjectMapper();
        // 要写入的数据对象，会自动转为json格式
        DataBuffer wrap = null;
        try {
            wrap = bufferFactory.wrap(objectMapper.writeValueAsBytes(exceptionResult));
            DataBuffer finalWrap = wrap;
            return response.writeWith(Mono.fromSupplier(() -> finalWrap));
        } catch (Exception e) {
            DataBuffer finalWrap1 = wrap;
            return response.writeWith(Mono.fromSupplier(() -> finalWrap1));
        }
    }

}

